package com.co.server.service.vote.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.co.common.dao.BaseDao;
import com.co.common.service.BaseServiceImpl;
import com.co.common.utils.PageReq;
import com.co.server.constant.Constant;
import com.co.server.dao.vote.TVoteDao;
import com.co.server.entity.user.aide.TUsersConstant;
import com.co.server.entity.vote.TChoice;
import com.co.server.entity.vote.TClass;
import com.co.server.entity.vote.TLabel;
import com.co.server.entity.vote.TVote;
import com.co.server.entity.vote.TVoteItem;
import com.co.server.entity.vote.TVoteLabel;
import com.co.server.entity.vote.TVoteUser;
import com.co.server.entity.vote.aide.TChoiceQuery;
import com.co.server.entity.vote.aide.TLabelQuery;
import com.co.server.entity.vote.aide.TVoteConstent;
import com.co.server.entity.vote.aide.TVoteForm;
import com.co.server.entity.vote.aide.TVoteItemQuery;
import com.co.server.entity.vote.aide.TVoteLabelQuery;
import com.co.server.entity.vote.aide.TVoteQuery;
import com.co.server.entity.vote.aide.TVoteUserQuery;
import com.co.server.entity.vote.aide.VoteForm;
import com.co.server.service.user.TUsersService;
import com.co.server.service.user.impl.UsersSession;
import com.co.server.service.vote.TChoiceService;
import com.co.server.service.vote.TClassService;
import com.co.server.service.vote.TLabelService;
import com.co.server.service.vote.TVoteItemService;
import com.co.server.service.vote.TVoteLabelService;
import com.co.server.service.vote.TVoteService;
import com.co.server.service.vote.TVoteUserService;

@Service
public class TVoteServiceImpl extends BaseServiceImpl<TVote, Integer> implements TVoteService {
    @Resource
    private TVoteDao tVoteDao;
    @Resource
    private TVoteItemService tVoteItemService;
    @Resource
    private TLabelService tLabelService;
    @Resource
    private TVoteLabelService tVoteLabelService;
    @Resource
    private TVoteUserService tVoteUserService;
    @Resource
    private TChoiceService tChoiceService;
    @Resource
    private TClassService tClassService;
    @Resource
    private TUsersService tUsersService;
    
    
    
    @Override
    protected BaseDao<TVote, Integer> getBaseDao() {
        return tVoteDao;
    }

	public void addVote4Form(VoteForm voteForm) {
		//保存投票表
		Date date = new Date();
		voteForm.setStatus(TVoteConstent.VOTE_STATUS_ACTIVE);
		voteForm.setDead(TVoteConstent.VOTE_NOT_DEAD);
		voteForm.setCreateTime(date);
		voteForm.setSupportNum(TVoteConstent.DEFAULE_SUPPORT_NUM);
		voteForm.setObjectNum(0);
		voteForm.setVoteNum(0);
		TClass tClass = tClassService.queryById(voteForm.getClassId());
		voteForm.setClassName(tClass.getName());
		add(voteForm);
		Integer id = voteForm.getId();
		//保存选项表
		List<TVoteItem> itemList = voteForm.getItemList();
		for (TVoteItem tVoteItem : itemList) {
			tVoteItem.setVoteId(id);
		}
		tVoteItemService.addInBatch(itemList);
		//保存标签表&标签投票关联表
		List<TLabel> labelList = voteForm.getLabelList();
		TLabel labelAvailable = null;
		Integer voteNum = 1;
		TLabelQuery tLabelQuery = new TLabelQuery();
		TVoteLabel tVoteLabel = null;
		Integer LabelId = null;
		for (TLabel tLabel : labelList) {
			//保存标签表 或者更新标签表数量
			tLabelQuery.setName(tLabel.getName());
			labelAvailable = tLabelService.queryOne(tLabelQuery);
			if(labelAvailable != null){
				voteNum = labelAvailable.getVoteNum();
				voteNum=voteNum+1;
				labelAvailable.setVoteNum(voteNum);
				tLabelService.updateById(labelAvailable);
				LabelId=labelAvailable.getId();
			}else{
				tLabel.setVoteNum(voteNum);
				tLabel.setCreateTime(new Date());
				tLabel.setStatus(Constant.STATUS_ACTIVE);
				tLabelService.add(tLabel);
				LabelId=tLabel.getId();
			}
			//保存投票标签关联表
			tVoteLabel = new TVoteLabel();
			tVoteLabel.setVoteId(id);
			tVoteLabel.setLabelId(LabelId);			
			tVoteLabelService.add(tVoteLabel);
			//新建投票，你获得5个积分
			tUsersService.updateUserGrade(voteForm.getCreateUserId(),TUsersConstant.USER_GRADE_FOR_ADD_VOTE);
		}
	}

	public void updateVote4Form(VoteForm voteForm) {
		Integer voteId = voteForm.getId();
		//删除标签表
		List<TLabel> labelList = voteForm.getLabelList();
		String name =null;
		TLabel labelAvailable = null;
		Integer voteNum = 1;
		TLabelQuery tLabelQuery = new TLabelQuery();
		for (TLabel tLabel : labelList) {
			name = tLabel.getName();
			tLabelQuery.setName(name);
			labelAvailable = tLabelService.queryOne(tLabelQuery);
			if(labelAvailable != null){
				if(labelAvailable.getVoteNum()>1){
					voteNum = labelAvailable.getVoteNum();
					voteNum=voteNum-1;
					tLabel.setVoteNum(voteNum);
					tLabelService.updateById(tLabel);					
				}else{
					tLabelService.deleteById(labelAvailable.getId());
				}
			}
		}
		
		//删除标签投票关联表
		TVoteLabelQuery tVoteLabelQuery = new TVoteLabelQuery();
		tVoteLabelQuery.setVoteId(voteId);
		tVoteLabelService.delete(tVoteLabelQuery);
		
		//删除选项表
		TVoteItemQuery tVoteItemQuery = new TVoteItemQuery();
		tVoteItemQuery.setVoteId(voteId);
		tVoteItemService.delete(tVoteItemQuery);
		//删除投票表
		TVoteQuery tVoteQuery = new TVoteQuery();
		tVoteQuery.setId(voteId);
		delete(tVoteQuery);
		//重新保存
		voteForm.setId(null);
		addVote4Form(voteForm);
	}

	public List<TVote> queryNotVoteByUserIdandIp(Integer userId,String ip) {
		return tVoteDao.selectNotVoteByUserIdandIp(userId,ip);
	}

	public Byte doVote(TVote tVoteForm,Integer userId,String ip) {
		if(tVoteForm == null){
			return Constant.STATUS_NOT_ACTIVE;
		}
		Integer voteId = tVoteForm.getId();
		if(voteId == null){
			return Constant.STATUS_NOT_ACTIVE;
		}
		
		//查询是否已投票
		Boolean voteFlg = getVoteFlg(userId, ip, voteId);
		if(voteFlg){
			return Constant.STATUS_NOT_ACTIVE;
		}
		
		//锁定投票表
		TVoteQuery tVoteQuery = new TVoteQuery();
		tVoteQuery.setId(voteId);
		tVoteQuery.setForUpdate(true);
		TVote vote = queryOne(tVoteQuery);
		Integer voteNum = vote.getVoteNum();
		if(voteNum == null){
			voteNum = 0;
		}
		//投票数量加1
		voteNum++;
		updateByIdSelective(new TVoteQuery(voteId,voteNum));
		
		//新增用户投票
		TVoteForm tVoteFormDto =(TVoteForm)tVoteForm;
		Collection<Integer> voteItemIds = tVoteFormDto.getVoteItemIds();
		TVoteUser tVoteUser = null;
		List<TVoteUser> voteUsers = new ArrayList<TVoteUser>();
		for (Integer voteItemId : voteItemIds) {
			tVoteUser = new TVoteUser();
			tVoteUser.setUserId(userId);
			tVoteUser.setVoteId(voteId);
			tVoteUser.setVoteIp(ip);
			tVoteUser.setVoteItemId(voteItemId);
			tVoteUser.setCreateTime(new Date());
			voteUsers.add(tVoteUser);
		}
		tVoteUserService.addInBatch(voteUsers);
		
		TVote tVote = queryById(voteId);
		//有人参与你的投票，你获得1个积分
		tUsersService.updateUserGrade(tVote.getCreateUserId(),TUsersConstant.USER_GRADE_FOR_FTOM_SOMEONE);
		return Constant.STATUS_ACTIVE;
	}

	public Byte doKnock(TChoice tChoice) {
		
		if(tChoice == null){
			return Constant.STATUS_NOT_ACTIVE;
		}
		Integer voteId = tChoice.getVoteId();
		TChoiceQuery tChoiceQuery = new TChoiceQuery();
		//查询是否已经点赞
		tChoiceQuery.setIp(tChoice.getIp());
		tChoiceQuery.setUserId(tChoice.getUserId());
		tChoiceQuery.setVoteId(voteId);
		TChoice choiceOld = tChoiceService.queryOne(tChoiceQuery);
		if(choiceOld != null){
			return Constant.STATUS_NOT_ACTIVE;
		}
		tChoice.setCreateTime(new Date());
		tChoiceService.add(tChoice);
		//锁定投票表
		TVoteQuery tVoteQuery = new TVoteQuery();
		tVoteQuery.setId(voteId);
		tVoteQuery.setForUpdate(true);
		TVote vote = queryOne(tVoteQuery);
		int supportNum = 0;
		int objectNum  = 0 ;
		objectNum = vote.getObjectNum();
		supportNum = vote.getSupportNum();			
		if(tChoice.getChoice()==2){
			//踩
			objectNum--;
		}else{
			//赞,投票数量加1
			supportNum++;
		}
		
		tVoteQuery.setSupportNum(supportNum);
		tVoteQuery.setObjectNum(objectNum);
		int checkDie = objectNum+supportNum;
		if(checkDie == 0){
			tVoteQuery.setDead(TVoteConstent.VOTE_DEAD);
			//你的投票死亡交叉，减20个积分
			TVote tVote = queryById(voteId);
			tUsersService.updateUserGrade(tVote.getCreateUserId(),TUsersConstant.USER_GRADE_FOR_VOTE_DEAD);
		}
		updateByIdSelective(tVoteQuery);
		return Constant.STATUS_ACTIVE;
	}

	public TVote getDefaultVote(UsersSession usersSession, PageReq pageReq,String ip) {
		//首选投票（首页第一个投票,或者是切换到的投票）
		TVote tVote = null;
		//查找该人未投票的放上面	
		Integer userId = usersSession.gettUsers().getUserId();
		//如果不是游客，则不允许多次投票
		List<TVote> notVoteList = queryNotVoteByUserIdandIp(userId,ip);
		if(CollectionUtils.isNotEmpty(notVoteList)){
			tVote=notVoteList.get(0);
		}else{
			pageReq.setPageSize(1);
			pageReq.setSort(new Sort(Direction.DESC,"t.create_time"));
			TVoteQuery tVoteQuery = new TVoteQuery();
			tVoteQuery.setDead(TVoteConstent.VOTE_NOT_DEAD);
			tVoteQuery.setStatus(Constant.STATUS_ACTIVE);
			Page<TVote> tmpList = queryPageList(tVoteQuery, pageReq);
			tVote=tmpList.getContent().get(0);
		}
		return 	tVote;	
	}

	public Boolean getVoteFlg(Integer userId, String voteIp, Integer voteId) {
		TVoteUserQuery tVoteUserQuery = new TVoteUserQuery();
		if(userId.equals(TUsersConstant.USER_GUEST_ID)){
			tVoteUserQuery.setVoteIp(voteIp);
		}
		tVoteUserQuery.setUserId(userId);
		tVoteUserQuery.setVoteId(voteId);
		List<TVoteUser> tVoteUserListTmp = tVoteUserService.queryList(tVoteUserQuery);
		if(CollectionUtils.isNotEmpty(tVoteUserListTmp)){
			return true;
		}
		return false;
	}

}